package cate.game.pvp.eliterace.handler;

import cate.game.pvp.eliterace.data.EliteRaceBetData;
import cate.game.pvp.eliterace.data.EliteRaceBetRecord;
import cate.game.pvp.eliterace.data.EliteRaceSpec;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;

import static cate.game.pvp.eliterace.data.EliteRaceBetRecord.INDEX_NAME;

public class BothEliteRaceBetOperation implements EliteRaceBetOperation {

    private final EliteRaceBetData betData;

    public BothEliteRaceBetOperation(Supplier<EliteRaceBetData> betDataSupplier) {
        this.betData = Objects.requireNonNull(betDataSupplier.get());
    }

    @Override
    public void addRecord(EliteRaceBetRecord record) {
        betData.addValue(record);
        betData.addIndex(INDEX_NAME, record.getSpec().toString(), record);
    }

    @Override
    public void bet(EliteRaceSpec spec, byte side, long coins) {
        Map<String, EliteRaceBetRecord> indexMap = betData.getIndex(INDEX_NAME);
        if (Objects.isNull(indexMap)) {
            return;
        }
        EliteRaceBetRecord record = indexMap.get(spec.toString());
        if (Objects.nonNull(record)) {
            record.update(side, coins);
        }
    }

    @Override
    public EliteRaceBetRecord query(EliteRaceSpec spec) {
        return betData.getIndex(INDEX_NAME).get(spec.toString());
    }

    @Override
    public List<EliteRaceBetRecord> all() {
        return betData.getValueList();
    }
}
